/*
 * Copyright (C) 2010 恒康信息科技有限公司
 * 版权所有
 */
package com.adb.shudu.ex;

import android.content.Context;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;

/**
 * 可以判断gallery停止滚动<br/>
 * 方法:在手离开gallery的时候开始一个线程,每500毫秒比较一下选中的项是否发生变化,如果没有发生变化结束线程,否则线程继续循环判断
 * 
 * @author yizhe
 * @date 2012-6-11
 */
public class HKAysLoadGallery extends Gallery {
	Context context;
	static int currentPosition;
	static int lastPosition;
	boolean isItemSelectedChange;// 选中的项是否发生了变化

	public HKAysLoadGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				currentPosition = position;
				isItemSelectedChange = true;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			System.out.println("ACTION_UP");
			JudgeTask task = new JudgeTask();
			task.execute(); // 手离开开始执行,判断gallery是否停止
		}
		return super.onTouchEvent(event);
	}

	// ------------------判断停止----------------//
	class JudgeTask extends AsyncTask<Object, Object, Object> {
		int i = -1;

		@Override
		protected Object doInBackground(Object... params) {

			// 每500毫秒执行一次判断,实验证明可以精确判断
			try {
				do {
					i++;
					lastPosition = currentPosition;
					Thread.sleep(500);
				} while (lastPosition != currentPosition);
			} catch (InterruptedException e) {
			}

			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			System.out.println("onPostExecute----- " + i + "---"
					+ currentPosition);
			// 已经停止
			// 如果选中的项发生了变化,执行...
			if (isItemSelectedChange) {
				if (null != onSelectedChange) {
					onSelectedChange.onSelectedChange(currentPosition);
				}
			}
			isItemSelectedChange = false;
			super.onPostExecute(result);
		}
	}

	protected HKGallerySelectedChange onSelectedChange;

	public void setOnSelectedChange(HKGallerySelectedChange c) {
		this.onSelectedChange = c;
	}

	/**
	 * 一次滑动只滚动一张图片
	 */
	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (velocityX > 0) {
			// 往左边滑动
			super.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
		} else {
			// 往右边滑动
			super.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
		}
		return false;
	}
}
